#ifndef __CHIP_PWM_HPP__
#define __CHIP_PWM_HPP__

#include <iostream>
#include <string>

extern "C"
{
#include <rtthread.h>
#include <rtdevice.h>
#include <math.h>
#include <stdint.h>
}

typedef enum
{
    chip_pwm_status_fail,
    chip_pwm_status_ok,
} chip_pwm_status;

typedef enum
{
    chip_pwm_drive_type_HIGH, //驱动设备高电平有效
    chip_pwm_drive_type_LOW, //驱动设备低电平有效
} chip_pwm_drive_type; //pwm驱动的设备有效电平类型

class CHIP_PWM
{
private:
    chip_pwm_status init_flag;
    uint8_t debug_flag;
    struct rt_device_pwm *pwm_dev;
    uint32_t pwm_period; //pwm周期  单位 ns
    uint32_t pwm_pulse_width; //pwm脉宽 单位 ns

    double pwm_ratio; //pwm 有效电平占比 0%-100%
    rt_mutex_t pwm_ratio_lock;

    uint32_t pwm_frequency; //PWM频率 单位 Hz
    chip_pwm_drive_type pwm_type; //pwm设备驱动电平类型
    int pwm_channel;

public:
    std::string pwm_dev_name;
private:
    chip_pwm_status _calculate_pwm_period(uint32_t pwm_frequency);
    void _calculate_pwm_pulse_width(double pwm_ratio);
public:
    ~CHIP_PWM();
    CHIP_PWM(std::string pwm_dev_name,
             int pwm_channel,
             chip_pwm_drive_type pwm_type,
             uint32_t pwm_frequency,
             double default_ratio);

    void CHIP_PWM_open_debug();
    void CHIP_PWM_close_debug();

    chip_pwm_status CHIP_PWM_open();
    chip_pwm_status CHIP_PWM_close();
    chip_pwm_status CHIP_PWM_change_channel(int new_channel);//更换通道成功后，旧通道默认关闭，新通道需要手动开启<CHIP_PWM_open()>
    chip_pwm_status CHIP_PWM_change_frequency(uint32_t new_freq);
    chip_pwm_status CHIP_PWM_change_duty_ratio(double new_ratio); //new_ratio:百分比 0-100

    uint8_t CHIP_PWM_read_latest_ratio();
    chip_pwm_status CHIP_PWM_read_init_status();
};

#endif /*__CHIP_PWM_HPP__*/

